import requests
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sendEmil import send_email
from datetime import datetime


token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJVU0VSX0xPR0lOX1JFRElTX0tFWV9QQzpML2hSUUtYVVp2SVNPZ2duL0p3enhRPT06MTE0LjI1NS4yMzAuMzAiLCJpYXQiOjE3NjM0NTIwNTcsImV4cCI6MTc2NDA1Njg1N30.J-CcS_3qnT0CBwdRzP4J5uV1fvGv-ZmhiCVDcsNyb_HRDD6HCw1S_Lf61TPfYUcDwgPQD5ocLMpj7J-i-U25fQ'
productids = [
	{'name':'RWA吴刚','id':'8cb9123fcd871b75b8fbd1df9aa9a693'},
	{'name':'RWA天蓬','id':'0c931eaf69b14eecd5d859fb6629aea5'},
	{'name':'RWA徽章','id':'ba6ef2f074dd9ef7e7aea5762d393bc2'},
	{'name':'钱镠金书铁券（复制品）','id':'386ab6ebfc416f0d3ec877fc1fa07a9c'},
	{'name':'文物精灵','id':'ea62e933acaadb2bde418949497119c8'},
	{'name':'星芒蛇','id':'6c3df4b6e0c1d3b28c76a6a6184a927b'},



]



import webbrowser

def buy(id,price):
	json_data = [
		{
			'saleRecordAmount': 1,
			'saleRecordId': id,
			'amountPay': price,
		},
	]
	headers = {
		'Accept': 'application/json, text/plain, */*',
		'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
		'Cache-Control': 'no-cache',
		'Connection': 'keep-alive',
		'Content-Type': 'application/json;charset=UTF-8',
		'Origin': 'https://www.theone.art',
		'Pragma': 'no-cache',
		'Referer': 'https://www.theone.art/buy/81c947cf76adb2e5d889dcacdba393b1',
		'Sec-Fetch-Dest': 'empty',
		'Sec-Fetch-Mode': 'cors',
		'Sec-Fetch-Site': 'same-site',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
		'authorization': token,
		'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
		'sec-ch-ua-mobile': '?0',
		'sec-ch-ua-platform': '"Windows"',
	}



	response = requests.post('https://api.theone.art/order/api/orderBuy/add', headers=headers, json=json_data).json()

	# Note: json_data will not be serialized by requests
	# exactly as it was in the original request.
	# data = '[{"saleRecordAmount":1,"saleRecordId":"81c947cf76adb2e5d889dcacdba393b1","amountPay":"75000"}]'
	# response = requests.post('https://api.theone.art/order/api/orderBuy/add', headers=headers, data=data)
	return response

while True:
	# 获取当前时间
	now = datetime.now()
	# 格式化时间为时分秒
	current_time = now.strftime("%H:%M:%S")
	# 打印时分秒
	print("----------------------------------------当前时间:", current_time)
	# 遍历所有商品ID
	for product_id in productids:
		headers = {
			'Accept': 'application/json, text/plain, */*',
			'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
			'Cache-Control': 'no-cache',
			'Connection': 'keep-alive',
			'Content-Type': 'application/json;charset=UTF-8',
			'Origin': 'https://www.theone.art',
			'Pragma': 'no-cache',
			'Referer': 'https://www.theone.art/derivative/8a6684374652c3dcf293eb03d51b990f/1',
			'Sec-Fetch-Dest': 'empty',
			'Sec-Fetch-Mode': 'cors',
			'Sec-Fetch-Site': 'same-site',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
			# 'authorization': token,
			'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
			'sec-ch-ua-mobile': '?0',
			'sec-ch-ua-platform': '"Windows"',
		}

		json_data = {
			'commodityId': product_id['id'],
			'pageCount': 1,
			'pageSize': 20,
			'sort': {
				'field': 2,
				'upOrDown': 1,
			},
		}
		try:
			response = requests.post('https://api.theone.art/market/api/saleRecord/list/v3', headers=headers, json=json_data).json()
			list = response['data']['records']
			if len(list) < 4:
				print(f"商品 {product_id['name']} 没有足够的商品信息")
				continue
			print(f"商品: {list[0]['commodity']['name']}, 价格: {list[0]['price']} / {list[1]['price']} / {list[2]['price']}")

			# 判断价格差异改为50%
			if float(list[0]['price']) <= float(list[1]['price']) * 0.4:
				print('发现低价商品!')
				res = buy(list[0]['id'],int(float(list[0]['price']))*100)
				print(res)
				if(res['code'] == 200):
					content = (f'商品: {list[0]["commodity"]["name"]}\n'
					           f'价格: {list[0]["price"]}\n'
					           f'商品列表 {list[1]["price"]}\n'
					           f'商品列表 {list[2]["price"]}\n'
					           f'商品列表 {list[3]["price"]}\n'
					           f'https://www.theone.art/mine/buy'
					           )
					send_email('唯一', content)
					print('https://www.theone.art/mine/buy')
					url = "https://www.douyin.com/user/self?from_tab_name=main&modal_id=7190605186274954536&showTab=like"
					webbrowser.open(url)
					exit()

		except Exception as e:
			# print(f'检查商品 {product_id} 时发生错误:', e)
			continue



